#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/statvfs.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#include <sched.h>
#include <ctype.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>

#include "public.h"

static void xy_network_led(void)
{
    extern unsigned char wflag;

    ac_traces(MSG_LEVEL_DEBUG, "wflag = %d\n", wflag);
    if (wflag == 0) {
        if (xy_network_4g_effectivenes()) {
            xy_trigger_mode_none(YELLOW);
            xy_led_brightness(YELLOW, LED_ON);
        }
        else {
            xy_led_slow_flash(YELLOW);
            ac_traces(MSG_LEVEL_INFO, "4G network invalid");
        }
    }
    else if (wflag == 1) {
        if (xy_network_wireless_effectivenes()) {
            xy_led_fast_flash(YELLOW);
        }
        else {
            xy_trigger_mode_none(YELLOW);
            xy_led_brightness(YELLOW, LED_OFF);
        }
    }
}

void * xy_network_thread(void)
{
    while (true) {
        xy_network_led();
        sleep(2);
    }
}

int xy_network_thread_run(void)
{
    pthread_attr_t attr;
    pthread_t network_id = 0;
    int ret = 0;
    void * ptr;

    pthread_attr_init(&attr);

    if (0 != (ret = pthread_create(&network_id, 
                                   &attr, 
                                   (void * (*)(void *))xy_network_thread, 
                                   NULL))) {
        ac_traces(MSG_LEVEL_ERROR, 
                  "create network led thread fail. error=%d", ret);
        return false;
    }

    ac_traces(MSG_LEVEL_INFO, 
              "network led thread create successfuly!");

    pthread_join(network_id, &ptr);

    return true;
}

